package org.msn.util;

import com.google.gson.Gson;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class JsonUtil {
    public static final Gson GSON = new Gson();

    public static String toJson(Object object) {
        return GSON.toJson(object);
    }

    public static <T> T formJson(Object object, Class<T> type) {
        String str = String.valueOf(object);
        str = str.replace("\\\"", "'");
        str = str.substring(0, str.length() - 1);
        return GSON.fromJson(str, type);
    }

    public static <T> T formJson(Map<String, Object> map, Class<T> type) {
        try {
            T temp = type.getConstructor().newInstance();

            BeanUtils.populate(temp, map);

            return temp;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
